package com.yf.aclient.activity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.yf.aclient.R;
import com.yf.aclient.adapter.PicViewAdapter;
import com.yf.aclient.adapter.PicViewAdapter.ViewHandler;

public class PictruesViewActivity extends Activity {
	//private Button uploadPic;
	

	private ListView listView;
	private List<JSONObject> myData = new ArrayList<JSONObject>();
	private HttpClient client;
	private String type="1";
	PicViewAdapter adapter;
	private ProgressDialog pd;
    
	private Handler handler =new Handler(){
		@Override
		//当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg){
			super.handleMessage(msg);
			//只要执行到这里就关闭对话框
			pd.dismiss();
		}
	};
	private void processThread(){
    	//构建一个下载进度条
    	pd= ProgressDialog.show(PictruesViewActivity.this, "载入数据", "正在载入数据…");
		//在新线程里执行长耗时方法
		constructData();
		//执行完毕后给handler发送一个空消息
		handler.sendEmptyMessage(0);
//    	new Thread(){
//    		public void run(){
//    			//在新线程里执行长耗时方法
//    			constructData();
//    			//执行完毕后给handler发送一个空消息
//    			handler.sendEmptyMessage(0);
//    		}
//    	}.start();
}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = this.getIntent();
		Bundle b = intent.getExtras();
		type=b.getString("type");
		setContentView(R.layout.picturesview);
		listView = (ListView) findViewById(R.id.pictruesList);
		client = new DefaultHttpClient();
		HttpParams params=client.getParams();
		//链接超时。
        HttpConnectionParams.setConnectionTimeout(params, 3000);   /////////
        //读取数据超时。
        HttpConnectionParams.setSoTimeout(params, 5000);
        processThread();
        adapter= new PicViewAdapter(this, myData);
		adapter.notifyDataSetChanged();
		
		listView.setAdapter(adapter);
		listView.setItemsCanFocus(false);
		// listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ViewHandler vHollder = (ViewHandler) view.getTag();
				// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
				             
			}
		});
	}

	// {"role":[{"id":66,"memo":"不错的图片","reourceUrl":"","resourceName":"测试中文sample_7.jpg","resourceType":1,"sharedTimes":1,"uploadTime":1327823113234,"userQq":"253908666"},{"id":67,"memo":"不错的图片abc","reourceUrl":"","resourceName":"测试中文sample_6.jpg","resourceType":1,"sharedTimes":1,"uploadTime":1327823113734,"userQq":"253908666"}]}
	/**
	 * 
	 * 从服务器构造数据。。。
	 */
	private void constructData() {
		//SharedPreferences setting=this.getPreferences(MODE_PRIVATE);
//		String serverUrl=;
		String getRolesUrl = getString(R.string.serverUrl)+"/task/getResouresResource.action";
		try {
			StringBuilder result = new StringBuilder("");
			HttpPost request = new HttpPost(getRolesUrl);
			// request.setParams(params);
			StringEntity reqEntity = new StringEntity("resourceType="+type);
			reqEntity.setContentType("application/x-www-form-urlencoded");
			request.setEntity(reqEntity);
			//request.set
			
			HttpResponse response = client.execute(request);
			
			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				result.append(line);
			}
			// JSONArray
			JSONArray jsonArray = new JSONArray(result.toString());
			result.delete(0, result.length());
			// JSONArray.
			if(jsonArray.length()<=0){
				JSONObject jso=new JSONObject();
				jso.put("id", "#");
				myData.add(jso);
				return;
			}
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jso = jsonArray.getJSONObject(i);
				jso.put("fileUrl", getString(R.string.serverUrl)+jso.getString("reourceUrl"));
				myData.add(jso);
			}
		} catch (Exception e) {
            Toast.makeText(this, "request:" + getRolesUrl + "出错！", Toast.LENGTH_LONG).show();
            handler.sendEmptyMessage(0);
			System.out.println("request:" + getRolesUrl + "出错！");
		}
	}


	/***
	 * 
	 * Activity 重新转到前台，刷新数据。。
	 */
	protected  void onResume(){
		super.onResume();
//        processThread();
		myData.clear();
        constructData();
      //  adapter= new PicViewAdapter(this, myData);
		adapter.notifyDataSetChanged();
	}
}
